const mongoose = require('mongoose')
const DB_URL = 'mongodb://120.79.237.49:27017/film'
// const DB_URL = 'mongodb://139.199.195.236:27017/film'

const isProduction = process.env.NODE_ENV === 'production'

if (isProduction) DB_URL = 'mongodb://127.0.0.1:27017/film'
mongoose.set('find', true);
const options = {
    dbName: 'film',
    useNewUrlParser: true,
    autoIndex: false, // Don't build indexes
    reconnectTries: Number.MAX_VALUE, // Never stop trying to reconnect
    reconnectInterval: 500, // Reconnect every 500ms
    poolSize: 10, // Maintain up to 10 socket connections
    // If not connected, return errors immediately rather than waiting for reconnect
    bufferMaxEntries: 0,
    connectTimeoutMS: 10000, // Give up initial connection after 10 seconds
    socketTimeoutMS: 45000, // Close sockets after 45 seconds of inactivity
    family: 4 // Use IPv4, skip trying IPv6
};
mongoose.connect(DB_URL, options)

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.on('connected', () => {
    // 连接成功
    console.log('connected to: ' + DB_URL);
});


const Schema = mongoose.Schema
const models = {
    film_type: {
        name: { type: String, require: true },
        value: { type: Number, require: true }
    },
    film: {
        name: { type: String, require: true },
        create_time: { type: String },
        pic_url: { type: String },
        down_url: { type: String },
        type: { type: Number, require: true, default: 3 },
        down_type: { type: Number, require: true }, // 0、迅雷 1、百度
        desc: { type: String },
        thunder_url: { type: String },
        baidu_url: {type: String},
        baidu_password: {type: String},
        show: { type: Boolean, require: true, default: true }
    },
    user: {
        username: { type: String, require: true },
        password: { type: String, require: true }
    }
}

for (let m in models) {
    mongoose.model(m, new mongoose.Schema(models[m]))
}


module.exports = {
    getModel: function (name) {
        return mongoose.model(name)
    }
}